﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace dxpSocket
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        bool UDPServerStartRec = false;
        static Socket UDPServer;
        Thread threadUDPServerRec;
        List<EndPoint> UDPServerEndPointList = new List<EndPoint>();
        private void btnUDPServerStartRec_Click(object sender, EventArgs e)
        {
            if (!UDPServerStartRec)
            {
                // 选择套接字连接方式
                UDPServer = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
                // 绑定服务端的端口
                UDPServer.Bind(new IPEndPoint(IPAddress.Any, Convert.ToInt32(tBoxUDPServerIPPoint.Text.Trim())));
                btnUDPServerTransmit.Enabled = true;
                UDPServerStartRec = true;
                btnUDPServerStartRec.Text = "停止接收";
                threadUDPServerRec = new Thread(() =>
                {
                    while (true)
                    {
                        EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                        byte[] buffer = new byte[1024];
                        int length = UDPServer.ReceiveFrom(buffer, ref point);//接收数据报
                        if (UDPServerEndPointList == null)
                        {
                            UDPServerEndPointList.Add(point);
                            cBoxUDPServerTraIPSelect.Items.Add(point.ToString());
                        }
                        if (!UDPServerEndPointList.Contains(point))
                        {
                            UDPServerEndPointList.Add(point);
                            cBoxUDPServerTraIPSelect.Items.Add(point.ToString());
                        }
                        rTBoxUDPServerIPinfo.AppendText("From " + point.ToString() + "\n" + Encoding.UTF8.GetString(buffer, 0, length) + "\n");
                        //string message = Encoding.UTF8.GetString(buffer, 0, length);
                        //rTBoxUDPServerContent.AppendText(message + "\n");
                    }
                });
                threadUDPServerRec.Start();
            }
            else
            {
                btnUDPServerStartRec.Text = "开始接收";
                btnUDPServerTransmit.Enabled = false;
                UDPServerStartRec = false;
                UDPServer.Close();
                UDPServer.Dispose();
                threadUDPServerRec.Abort();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btnUDPServerTransmit.Enabled = false;
            UDPServerStartRec = false;
            RichTextBox.CheckForIllegalCrossThreadCalls = false;
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void btnUDPServerTransmit_Click(object sender, EventArgs e)
        {
            if (UDPServerEndPointList.Count == 0)
            {
                MessageBox.Show("ip为空");
                return;
            }
            if (rTBoxUDPServerContent.Text != "")
            {
                EndPoint point = UDPServerEndPointList.ToArray()[cBoxUDPServerTraIPSelect.SelectedIndex];
                UDPServer.SendTo(Encoding.UTF8.GetBytes(rTBoxUDPServerContent.Text), point);
            }

        }


        static Socket UDPClient;
        Thread threadUDPClientRec;
        List<EndPoint> UDPClientEndPointList = new List<EndPoint>();
        bool UDPClientStarListen = false;
        private void btnUDPClientListen_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tBoxUDPClientHostPoint.Text))
            {
                return;
            }
            if (UDPClientStarListen)
            {
                UDPClientStarListen = false;
                btnUDPClientListen.Text = "开始监听";
                threadUDPClientRec.Abort();
                UDPClient.Close();
                UDPClient.Dispose();
            }
            else
            {
                UDPClientStarListen = true;
                btnUDPClientListen.Text = "停止监听";
                //定义网络类型，数据连接类型和网络协议UDP
                UDPClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                UDPClient.Bind(new IPEndPoint(IPAddress.Any, Convert.ToInt32(tBoxUDPClientHostPoint.Text.Trim())));
                threadUDPClientRec = new Thread(() =>
                {
                    while (true)
                    {
                        EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                        byte[] buffer = new byte[1024];
                        int length = UDPClient.ReceiveFrom(buffer, ref point);//接收数据报
                        if (UDPClientEndPointList == null)
                        {
                            UDPClientEndPointList.Add(point);

                        }
                        if (!UDPClientEndPointList.Contains(point))
                        {
                            UDPClientEndPointList.Add(point);
                        }
                        rTBoxUDPClientRec.AppendText("From " + point.ToString() + "\n" + Encoding.UTF8.GetString(buffer, 0, length) + "\n");
                    }
                });
                threadUDPClientRec.Start();
            }
        }

        private void btnUDPClientTransmit_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(tBoxrUDPClientIP.Text) || string.IsNullOrEmpty(tBoxrUDPClientPoint.Text) || string.IsNullOrEmpty(tBoxUDPClientHostPoint.Text))
            {
                return;
            }
            UDPClient.SendTo(Encoding.UTF8.GetBytes(rTBoxUDPClientTransmit.Text), new IPEndPoint(IPAddress.Parse(tBoxrUDPClientIP.Text), Convert.ToInt32(tBoxrUDPClientPoint.Text.Trim())));
        }
    }
}
